import '@lhy-assist/vue3/dist/style.css'
import { App } from 'vue'
import { AxiosError } from 'axios'
import { api } from '@/config'
import { ApiResponse, ApiResponseCode } from '@/service/api.service'
import { Options, vue3Frame } from '@lhy-assist/vue3'
import { Loader } from '@lhy-assist/vue3-element'
import { errorHandler, exceptionHandler, unauthorizedHandler } from './error-handler'

export default {
  install(app: App) {
    app.use(vue3Frame, {
      plugins: {
        axios: {
          defaults: {
            baseURL: api,
          } as any,
          interceptor: {
            authorization: false,
            requestDataFormat: false,
            responseData: { enabled: true },
            loading: {
              show: () => Loader.show(),
              hide: () => Loader.hide(),
            },
            responseErrorHandle: {
              httpStatus: {
                200: (err: AxiosError<ApiResponse>) => {
                  switch (err.response?.data?.code) {
                    case ApiResponseCode.WARNING:
                      errorHandler(err)
                      break
                    case ApiResponseCode.UNAUTHORIZED:
                      unauthorizedHandler(err)
                      break
                    default:
                      exceptionHandler(err)
                  }
                },
                401: (err: AxiosError<ApiResponse>) => {
                  unauthorizedHandler(err)
                },
              },
              others: exceptionHandler,
            },
          },
        },
      },
    } as Partial<Options>)
  },
}
